import React, { useEffect } from 'react';
import { connect } from 'umi';
import _ from 'lodash';

import { PageLoading, TRDefault } from '@/components/index.js';
import { useTRState } from '@/pages/ETrade/components';
import { HttpCode } from '#/utils/contacts.js';
import { getGansuStations } from '@/pages/GanSuDaTang/services';
import { exportFn, table1, table2 } from './helper/tables';
import ChartsBox from './component/charts';
import TableBox from './component/table';
import styles from './index.less';
import { HeaderSearch } from './component/headerSearch';
import {
  spotMarketClearanceElectricityPrices,
  tradeSituationQuery,
  executePowerTrading,
  situationDescription,
  outPutChartData,
} from '@/pages/GanSuDaTang/Report/DayTransaction/service';
import { chart1, chart2 } from '@/pages/GanSuDaTang/Report/DayTransaction/helper/charts';

const MyComponent = ({ menuCode, buttonPermissions }) => {
  /** data */
  const exportKey = 'xxxxxxxxxxxxx';
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey), // power
    error: '',
    dataHeader: [],
    dataSource: [],
    stations: [],
    spinning: true, // form
    form: null,
    loading: true,
    charts: [],
    tables: [],
    chartImgs: [],
    moreText: '',
    date: '',
    fpfx: '',
    pointData: {},
  });

  useEffect(() => {
    fetchPower().then();
  }, []);

  /** methods */
  const fetchPower = async () => {
    // 数据权限
    const { error, stations } = await getGansuStations(menuCode);
    setState({
      error,
      stations,
      spinning: false,
    });
  };
  const fetchData = async (date, stationIdList) => {
    fetchDayData(date, stationIdList);
  };

  const fetchDayData = async (searchDate, stationIdList) => {
    // 数据请求
    // setState({ loading: true });
    // 数据需要解析在这儿处理好
    if (!searchDate) {
      return;
    }
    setState({
      loading: true,
    });
    let date = searchDate.format('YYYY-MM-DD');
    let param = {
      stationIdList,
      date,
    };
    let table_data1 = {};
    let table_data2 = {};
    let chart_data1 = {};
    let chart_data2 = {};
    let chart_data3 = {};
    let moreText = '暂无数据';
    let fpfx = '暂无数据';
    let res = await Promise.all([
      spotMarketClearanceElectricityPrices(param),
      tradeSituationQuery(param),
      executePowerTrading(param),
      situationDescription(date),
      outPutChartData(date),
    ]);
    if (res[0].statusCode === HttpCode.SUCCESS && res[4].statusCode === HttpCode.SUCCESS) {
      chart_data1 = res[4]?.data || {};
      chart_data2 = res[0]?.data?.areaDate?.heDong || {};
      chart_data3 = res[0]?.data?.areaDate?.heXi || {};
    }
    const charts = [
      chart1(chart_data1, _tooltipFormatter.bind(this)),
      chart2(chart_data2),
      chart2(chart_data3),
    ];
    if (res[1].statusCode === HttpCode.SUCCESS && res[2].statusCode === HttpCode.SUCCESS) {
      table_data1 = res[1]?.data || {};
      table_data2 = res[2]?.data?.listDate || {};
    }
    const tables = [table1(table_data1), table2(table_data2)];
    if (res[3].statusCode === HttpCode.SUCCESS && res[3].data.length > 0) {
      let text = res[3].data[0].situationDescription;
      if (text.length > 0) {
        let index = text.indexOf('复盘分析：\n');
        moreText = text.slice(6, index - 4);
        fpfx = text.slice(index + 6);
      }
    }
    setState({
      charts,
      tables,
      loading: false,
      moreText,
      date,
      fpfx,
    });
  };
  const _tooltipFormatter = (params) => {
    if (params.length > 0 && params[0].data != state.pointData) {
      setState({
        pointData: params[0].data,
      });
    }
  };
  const onExport = () => {
    // 导出，用下面这个封装的方法，有空可以去看下源码
    // if (!state.canExport) return Message.info('请联系管理员获取相关权限');
    exportFn(state.tables, state.chartImgs);
  };
  const _getContent = () => {
    return state.loading ? (
      <PageLoading />
    ) : (
      <>
        <ChartsBox
          charts={state.charts}
          date={state.date}
          hoverData={state.pointData}
          setChartImgs={(chartImgs) => {
            setState({ chartImgs });
          }}
        />
        <TableBox tables={state.tables} moreText={state.moreText} fpfx={state.fpfx} />
      </>
    );
  };

  /** render */
  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.stations?.length) return <TRDefault type="lock" />;
  return (
    <div className={styles.page}>
      <div className={styles.head}>
        <HeaderSearch
          setFatherState={setState}
          stations={state.stations}
          onExport={onExport}
          fetchData={fetchData}
        />
      </div>
      <div className={styles.main}>{_getContent()}</div>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(MyComponent);
